<?php
/**
 * Created by PhpStorm.
 * User: surface
 * Date: 2019/1/11
 * Time: 21:28
 */
namespace app\common\model;

use app\common\model\Stock as StockModel;

class StockList extends Common
{
    const TYPE_SALE = 1;//销售出库
    const TYPE_RETURN = 2;//取消订单入库
    const TYPE_INCOME = 3;//手工入库
    const TYPE_CHECKOUT = 4;//手工出库

    const  TYPE_OUT = 1;//出库
    const  TYPE_IN = 2;//入库

    /**库存变动
     * @param $goods_id
     * @param $quantity
     * @param $type
     * @param string $memo
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function change($user_id, $goods_id, $quantity, $type, $memo = "", $room_bn = "" ){

        $stockModel = new StockModel();
        $stock = $stockModel->field('*')->where(['goods_id'=>$goods_id])->find();
        if(self::TYPE_SALE == $type || self::TYPE_CHECKOUT == $type){
            $stock['stock'] -= $quantity;
            $log['type'] = 1;
        }else{
            $stock['stock'] += $quantity;
            $log['type'] = 2;
        }
        $stockModel->save(['stock' => $stock['stock']], ['id' => $stock['id']]);
        $log['goods_id'] = $goods_id;
        $log['quantity'] = $quantity;
        $log['ctime'] = time();
        $log['memo'] = $memo;
        if(self::TYPE_SALE == $type){
            $log['memo'] = "销售出库";
        }
        if(self::TYPE_RETURN == $type){
            $log['memo'] = "取消订单入库";
        }
        $log['user_id'] = $user_id;
        $log['room_bn'] = $room_bn;
        $this->insertGetId($log);
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data'=> []
        ];
        return $result;
    }
}
